package com.poisonh.unifiedauth.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dao.UserinfoDaoImpl;
import com.poisonh.unifiedauth.model.UserInfoModel;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.Photoutils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.poisonh.unifiedauth.widget.CircleImageView;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONObject;

import java.io.File;

/**
 * 设置用户头像
 * Created by PoisonH on 2016/6/27.
 */
public class SettingHeadImgActivity extends BaseActivity implements View.OnClickListener
{
    private AutoRelativeLayout mARLChoose;
    private AutoRelativeLayout mARLShot;
    private CircleImageView mMyHead;

    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "head.png";

    /* 请求识别码 */
    private final int CODE_GALLERY_REQUEST = 0xa0;
    private final int CODE_CAMERA_REQUEST = 0xa1;
    private final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private int output_X = 80;
    private int output_Y = 80;
    private String imagePath = "null";

    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_settinghead);
        initTitleView();
        initView();
    }

    @Override
    protected void initView()
    {
        setTitleTxt("设置头像");
        mRightBtn.setVisibility(View.GONE);
        mARLChoose = (AutoRelativeLayout) findViewById(R.id.arl_setting_head_a);
        mARLShot = (AutoRelativeLayout) findViewById(R.id.arl_setting_head_b);
        mARLChoose.setOnClickListener(this);
        mARLShot.setOnClickListener(this);
        mLeftBtn.setOnClickListener(this);
        mMyHead = (CircleImageView) findViewById(R.id.setting_my_head);
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setText("保存");
        mTvRight.setOnClickListener(this);
        if (mStrUserHeadUrl != null)
        {
            Glide.with(this).load(mStrUserHeadUrl).into(mMyHead);
        }
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.arl_setting_head_a:
                choosePhoto();
                break;
            case R.id.arl_setting_head_b:
                ShotPhoto();
                break;
            case R.id.ib_left_btn:
                finish();
                break;
            case R.id.tv_right_txt:
                if (!imagePath.equals("null"))
                {
                    SVProgressHUD.showWithStatus(this, "加载中...");
                    upUserHead();
                } else
                {
                    ToastUtils.showToast(SettingHeadImgActivity.this, "头像获取失败");
                }

                break;
        }
    }

    /**
     * 拍照
     */
    private void ShotPhoto()
    {
        Intent mShotPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        mShotPhoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));

        startActivityForResult(mShotPhoto, CODE_CAMERA_REQUEST);
    }

    /**
     * 选择相册
     */
    private void choosePhoto()
    {
        Intent intentFromGallery = new Intent();
        // 设置文件类型
        intentFromGallery.setType("image/*");
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);
    }


    /**
     * 裁剪原始的图片
     */
    public void cropRawPhoto(Uri uri)
    {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        // 设置裁剪
        intent.putExtra("crop", "true");

        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", output_X);
        intent.putExtra("outputY", output_Y);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, CODE_RESULT_REQUEST);
    }

    /**
     * 提取保存裁剪之后的图片数据，并设置头像部分的View
     */
    private void setImageToHeadView(Intent intent)
    {
        Bundle extras = intent.getExtras();
        if (extras != null)
        {
            Bitmap photo = extras.getParcelable("data");
            //uploadPic(photo);
            imagePath = Photoutils.savePhoto(photo, Environment.getExternalStorageDirectory().getAbsolutePath(), "head");
            mMyHead.setImageBitmap(photo);
        }
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard()
    {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {

        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED)
        {
            //  Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }

        switch (requestCode)
        {
            case CODE_GALLERY_REQUEST:
                cropRawPhoto(intent.getData());
                break;

            case CODE_CAMERA_REQUEST:
                if (hasSdcard())
                {
                    File tempFile = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
                    cropRawPhoto(Uri.fromFile(tempFile));
                } else
                {
                    Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG).show();
                }

                break;

            case CODE_RESULT_REQUEST:
                if (intent != null)
                {
                    setImageToHeadView(intent);
                }

                break;
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }


    /**
     * 更新用户头像
     */
    private void upUserHead()
    {
        File tempFile = new File(imagePath);
        HttpParams params = new HttpParams();
        params.put("id", mStrUserId);
        params.put("token", mStrUserToken);
        params.put("headImg", tempFile);

        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.CHANGEHEAD, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                ToastUtils.showToast(SettingHeadImgActivity.this, "头像更换成功");
                SVProgressHUD.dismiss(SettingHeadImgActivity.this);
                sendChangeHeadBR(response);
                finish();
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(SettingHeadImgActivity.this, "头像更换失败");
                SVProgressHUD.dismiss(SettingHeadImgActivity.this);
            }
        });
    }

    /**
     * 发送更改头像的广播
     */
    private void sendChangeHeadBR(String response)
    {
        //根据id查询用户
        UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(this);
        try
        {
            UserInfoModel model = mUserinfoDaoImpl.queryReturnOne(mStrUserId);
            JSONObject object = new JSONObject(response);
            JSONObject data = object.getJSONObject("results");
            model.setmStrHeadUrl(ConstantUitls.REQUEDT_IMG_URL + data.getString("headImgUrl"));
            mUserinfoDaoImpl.commit();
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        Intent mInent = new Intent("HEAD_CHANGE");
        this.sendBroadcast(mInent);
    }

}
